package cn.codenest;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * create by: Hyman
 * description: 普通socket的服务端，阻塞等待客户端的连接，接受从客户端传递过来的数据，打印到标准输出上。
 * create time: 2021/4/20
 */
public class Server {

    private final static int BUFF_SIZE = 1024;
    private final static int SERVER_PORT = 10020;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
        serverSocket.setReceiveBufferSize(BUFF_SIZE);
        Socket clientSocket = serverSocket.accept();
        System.out.println(clientSocket.getInetAddress().getHostAddress() + "SUCCESS TO CONNECT...");
        InputStream in = clientSocket.getInputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while (true) {
            len = in.read(buf);
            String str = new String(buf, 0, len);
            System.out.println("client saying: " + str);
            if (str.equals("quit")) {
                break;
            }
        }
        if(in!=null){
            in.close();
        }
        if(clientSocket.isConnected()){
            clientSocket.close();
        }
        serverSocket.close();
    }
}
